package com.newtype.meeting.server.service;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.newtype.meeting.client.model.Account;
import com.newtype.meeting.client.service.LoginService;
import com.newtype.meeting.server.PMF;
import com.newtype.meeting.shared.LoginInfo;

/**
 * 登录验证实现类
 * @author 汪恭泽
 *
 */
@SuppressWarnings("serial")
public class LoginServiceImpl extends RemoteServiceServlet implements
		LoginService {
	//	private static Logger logger = Logger.getLogger(LoginServiceImpl.class.getName());

	@Override
	public LoginInfo googleLogin(String requetUri) {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		LoginInfo loginInfo = new LoginInfo();
		if (user != null) {
			loginInfo.setLoggedIn(true);
			loginInfo.setEmailAddress(user.getEmail());
			loginInfo.setNickname(user.getNickname());
			loginInfo.setAdmin(userService.isUserAdmin());
			loginInfo.setLogoutUrl(userService.createLogoutURL(requetUri));
		} else {
			loginInfo.setLoggedIn(false);
			loginInfo.setLoginUrl(userService.createLoginURL(requetUri));
		}
		return loginInfo;
	}

	/**
	 * 检查邮箱是否存在
	 */
	@SuppressWarnings("unchecked")
	@Override
	public boolean isEmailExist(String email) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Account.class, "email == param");
		q.declareParameters("String param");
		try {
			List<Account> results = (List<Account>) q.execute(email);
			if (results.size() > 0) {
				return true;
			} else {
				return false;
			}
		} finally {
			q.closeAll();
			pm.close();
		}
	}

}
